import CustomerTable from "@/components/CustomerTable";
import DictTag from "@/components/DictTag";
import { CloudDownloadOutlined, DeleteOutlined, ExclamationCircleFilled, PlusOutlined } from "@ant-design/icons";
import { ActionType, PageContainer, ProColumns, ProTable } from "@ant-design/pro-components";
import { Button, Divider, FormInstance, Input, Modal, Popconfirm, Space, Switch, Typography, message } from "antd";
import React, { useEffect, useRef, useState } from "react";
import OssConfigDetails from "./components/ConfigDetails";
import OssConfigForm, { OssConfigFormData } from "./components/ConfigForm";
import { getDict } from "@/services/api/module/system/dict";
import { getPageList, remove, save, update, changeStatus as updateStatus } from "@/services/api/module/tenant/storage/config";
import FilterDrawer from "@/components/FilterDrawer";
import ImportExportDropdown from "@/components/ImportExportDropdown";
import Blockquote from "@/components/Blockquote";
const { confirm } = Modal;
import { dict } from "@/utils/DictionaryCacheManager";

const OssFile: React.FC = () => {
	const formTableRef = useRef<FormInstance>();
	const [open, setOpen] = useState<boolean>(false);
	const [dataSource, setDataSource] = useState<API.Setting.StorageConfigVo | undefined>(undefined);
	const [formOpen, setFormOpen] = useState<boolean>(false);
	const actionRef = useRef<ActionType>();
	const [currentId, setCurrentId] = useState<number | undefined>(undefined);
	const [selectedRows, setSelectedRows] = useState<API.Setting.StorageConfigVo[]>([]);
	const [statusOptions, setStatusOptions] = useState<any>([]);
	const [accessPolicyOptions, setAccessPolicyOptions] = useState<any>([]);
	const [httpsOptions, sethttpsOptions] = useState<any>([]);
	/** 国际化配置 */

	useEffect(() => {
		dict.getDict("sys_normal_disable").then(data => {
			setStatusOptions(data);
		});
		dict.getDict("sys_oss_access_policy").then(data => {
			setAccessPolicyOptions(data);
		});
		dict.getDict("sys_is_https").then(data => {
			sethttpsOptions(data);
		});
	}, []);
	// 列定义
	const columns: ProColumns<API.Setting.StorageConfigVo>[] = [
		{
			title: "配置键",
			dataIndex: "configKey",
			valueType: "text"
		},
		{
			title: "存储桶",
			dataIndex: "bucketName",
			valueType: "text"
		},
		{
			title: "端点",
			dataIndex: "endpoint",
			valueType: "text",
			search: false,
			ellipsis: true,
			copyable: true
		},
		{
			title: "自定义域名",
			dataIndex: "domain",
			valueType: "text",
			search: false
		},
		{
			title: "区域",
			dataIndex: "region",
			valueType: "text",
			search: false
		},
		{
			title: "前缀",
			dataIndex: "prefix",
			valueType: "text",
			search: false
		},
		{
			title: "桶权限",
			dataIndex: "accessPolicy",
			valueType: "select",
			valueEnum: accessPolicyOptions,
			render: (_, record) => {
				return <DictTag type="tag" enums={accessPolicyOptions} value={record?.accessPolicy} />;
			}
		},
		{
			title: "启用状态",
			dataIndex: "status",
			valueType: "select",
			valueEnum: statusOptions,
			render: (_, record) => {
				return (
					<Switch
						checked={record.status === "0"}
						defaultChecked
						onChange={value => {
							changeStatusAlert(record?.id, value, record?.bucketName, record?.configKey);
						}}
					/>
				);
			}
		},
		{
			title: "操作",
			dataIndex: "option",
			valueType: "option",
			fixed: "right",
			render: (_, record: any) => {
				return (
					<>
						<Space size={1} split={<Divider type="vertical" />}>
							<Typography.Link
								key="editorBtn"
								onClick={() => {
									setFormOpen(true);
									setCurrentId(record.id);
								}}
							>
								修改
							</Typography.Link>
							<Typography.Link
								key="detailsBtn"
								onClick={() => {
									setOpen(true);
									setDataSource(record);
								}}
							>
								详情
							</Typography.Link>
							<Popconfirm
								placement="bottomRight"
								title="提示"
								description={`确认要删除该 "${record.bucketName}" 存储桶配置吗`}
								key="remove"
								onConfirm={async () => handleRemove(record.id)}
								okText="确认"
								cancelText="取消"
							>
								<Typography.Link type="danger" key="removeBtn">
									删除
								</Typography.Link>
							</Popconfirm>
						</Space>
					</>
				);
			}
		}
	];
	// 删除
	const handleRemove = async (ids: number | Array<number | undefined>) => {
		return new Promise((reslove, reject) => {
			remove(ids)
				.then((res: any) => {
					message.success(res.msg);
					if (actionRef.current) {
						actionRef.current.reload();
					}
					reslove(true);
				})
				.catch(() => {
					reject(true);
				});
		});
	};
	// 删除警告提示
	const showRemoveConfirm = (ids: Array<number | undefined>, bucketName: Array<string>) => {
		confirm({
			title: "警告",
			icon: <ExclamationCircleFilled />,
			content: `确认删除删除 ${bucketName} 的配置吗?`,
			onOk() {
				return handleRemove(ids);
			},
			onCancel() {}
		});
	};

	// 关闭表单刷新列表
	const handleTableForm = async () => {
		setFormOpen(false);
		setCurrentId(undefined);
		actionRef?.current?.reload();
	};

	// 保存
	const handleSave = async (values: OssConfigFormData) => {
		return new Promise((resolve, reject) => {
			save({ ...values } as OssConfigFormData)
				.then((res: any) => {
					message.success(res.msg);
					handleTableForm();
					resolve(true);
				})
				.catch(() => {
					reject(false);
				});
		});
	};
	// 編輯
	const handleUpdate = async (values: OssConfigFormData) => {
		return new Promise((resolve, reject) => {
			update({ ...values } as OssConfigFormData)
				.then((res: any) => {
					message.success(res.msg);
					handleTableForm();
					resolve(true);
				})
				.catch(() => {
					reject(false);
				});
		});
	};
	// 弹出警告
	const changeStatusAlert = async (id: string | number | undefined, checked: boolean, bucketName: string, configKey: string) => {
		const text = checked ? "启用" : "停用";
		confirm({
			title: `提示`,
			content: `确认要${text}，存储桶为：${bucketName} 的配置吗`,
			okText: "确认",
			cancelText: "取消",
			async onOk() {
				return changeStatus({
					id: id,
					status: checked ? "0" : "1",
					configKey: configKey
				} as API.Setting.StorageConfigBo);
			}
		});
	};
	// 修改状态
	const changeStatus = async (values: API.Setting.StorageConfigBo) => {
		return new Promise((resolve, reject) => {
			updateStatus({ ...values } as API.Setting.StorageConfigBo)
				.then((res: any) => {
					message.success(res.msg);
					handleTableForm();
					resolve(true);
				})
				.catch(() => {
					reject(false);
				});
		});
	};

	const [searchFormValue, setSearchFormValue] = useState<any>(undefined);
	const [searchValue, setSearchValue] = useState<any>(undefined);
	//数据请求
	const tableDataRequest = async (params: {} | undefined) => {
		return await getPageList({ ...searchFormValue, ...searchValue }).then((data: any) => {
			return data;
		});
	};
	const handleOnSearch = async (value: any) => {
		setSearchValue({
			userName: value
		});
		actionRef.current?.reload();
	};
	return (
		<>
			<CustomerTable<API.Setting.StorageConfigVo>
				actionRef={actionRef}
				// headerTitle={"存储桶配置"}
				tableStyle={{ minHeight: "calc(100vh - 200px)" }}
				formRef={formTableRef}
				rowKey="id"
				key="ossConfig"
				toolbar={{
					search: (
						<Space>
							<Input.Search placeholder="配置键" allowClear style={{ width: 280 }} onSearch={handleOnSearch} />
							<FilterDrawer
								columns={columns}
								tableActionRef={actionRef}
								onReset={() => {
									setSearchFormValue(undefined);
									actionRef?.current?.reload();
								}}
								onSubmit={(values: any) => {
									setSearchFormValue(values);
									actionRef?.current?.reload();
								}}
							/>
						</Space>
					)
				}}
				search={false}
				pagination={{
					showQuickJumper: true,
					showSizeChanger: true
				}}
				request={tableDataRequest}
				// @ts-ignore
				toolBarRender={() => {
					return (
						<>
							<Button
								type="primary"
								key="add"
								onClick={async () => {
									setFormOpen(true);
								}}
							>
								<PlusOutlined /> 添加存储桶
							</Button>
							<ImportExportDropdown key="import" columns={columns} onExport={function (values: any): Promise<any> {}} />
							{selectedRows.length > 0 && (
								<Button
									type="primary"
									key="remove"
									danger
									onClick={async () => {
										showRemoveConfirm(
											Array.from(selectedRows, ({ id }) => id),
											Array.from(selectedRows, ({ bucketName }) => bucketName)
										);
									}}
								>
									<DeleteOutlined />
									批量删除
								</Button>
							)}
						</>
					);
				}}
				columns={columns}
				rowSelection={{
					onChange: (_, selectedRows) => {
						setSelectedRows(selectedRows);
					}
				}}
				tableAlertRender={false}
				tableAlertOptionRender={selectedRowKeys => {
					console.log(selectedRowKeys);
					return (
						<Space size={10}>
							<a style={{ marginInlineStart: 8 }} onClick={() => selectedRowKeys.onCleanSelected()}>
								取消选择
							</a>
							{/* <Popconfirm
								placement="bottomRight"
								title="提示"
								description={`确定删除这些用户：${selectedRowKeys.selectedRows.map(item => {
									return item?.roleName;
								})} 的用户吗？`}
								onConfirm={() => {}}
								okText="确认"
								cancelText="取消"
							>
								<a type="link" key="remove" hidden={selectedRows?.length === 0} onClick={async () => {}}>
									批量删除
								</a>
							</Popconfirm> */}

							<a key="export" onClick={async () => {}}>
								批量导出
							</a>
						</Space>
					);
				}}
			/>
			<OssConfigDetails
				dataSource={dataSource}
				open={open}
				accessPolicyOptions={accessPolicyOptions}
				statusOptions={statusOptions}
				onCancel={() => {
					setOpen(false);
				}}
			/>
			<OssConfigForm
				open={formOpen}
				onCancel={() => {
					setFormOpen(false);
					setCurrentId(undefined);
				}}
				onSubmit={async (values: OssConfigFormData) => {
					return values.id ? await handleUpdate(values) : await handleSave(values);
				}}
				id={currentId}
				httpsOptions={httpsOptions}
				accessPolicyOptions={accessPolicyOptions}
			/>
		</>
	);
};

export default OssFile;
